# -*- coding: utf8 -*-
'''
Created on 2009/10/26

@author: matianyi
'''

from StringIO import StringIO
from django.utils import simplejson as json
from google.appengine.api import users
from google.appengine.ext import db, webapp
from org.andolphin import *
from org.andolphin.models import *
import datetime

class PayListPage(webapp.RequestHandler):
    def get(self):
        r = Result(RESULT_METHOD_NOT_ALLOWED, RESULT_METHOD_NOT_ALLOWED_MSG,{})
        render_json(self.response, r)
        
    def post(self):
        r = None
        username = self.request.headers['username'];
        post_body = self.request.get('post_body','[]')
        count = 0
        try:
            obj = json.loads(post_body, encoding='utf-8')
            for bk in obj:
                event_date = bk.eventDate
                if event_date:
                    date = datetime.datetime.strptime(event_date, '%Y-%m-%d').date()
                    payments = Payment.gql('WHERE event_date = :1 and user_id = :2', [date, username]).fetch()
                    for p in payments:
                        p.delete()
                    for pay in bk.paylist:
                        p = Payment(
                                user_id = username,
                                sequence = pay.sequence,
                                amount = pay.amount,
                                balance = pay.balance,
                                category = pay.category,
                                description = pay.description,
                                event_date = date,
                                last_updated = datetime.datetime.strptime(pay.last_updated, '%Y-%m-%d %H:%M:%S')
                            )
                        p.put()
                        count = count + 1
                else:
                    r = Result(RESULT_INPUT_ERROR, RESULT_INPUT_ERROR_MSG,{})
                    render_json(self.response, r)
                    return
                if count > 0:
                    user = User.gql('WHERE user_id = :1',[username])
                    if user:
                        user.sync_version = user.sync_version + 1
                        user.put() 
        except ValueError:
                r = Result(RESULT_INPUT_ERROR, RESULT_INPUT_ERROR_MSG,{})
                render_json(self.response, r)
                return

        r = Result(RESULT_SUCCESS, RESULT_SUCCESS_MSG, {'count':count})    
        render_json(self.response, r)